package com.easy.back.utils.sendCode;


import cn.hutool.core.lang.UUID;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.easy.back.pojo.EmailBody;
import com.easy.back.pojo.R;
import com.easy.back.utils.ValidateCodeUtils;
import com.easy.back.utils.mq.MessageRocketProducer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 邮件发送处理工具类
 *
 * @author RuoYu
 * @date 2022/11/18
 */
@Component
public class SMSUtils {

    @CreateCache(area = "suiyizu", name = "login_", expire = 300, timeUnit = TimeUnit.SECONDS)
    private Cache<String, String> codeCache;

    @Autowired
    private MessageRocketProducer messageRocketProducer;

    /**
     * 发送邮件
     *
     * @param phone 电话
     * @return {@link R}
     */
    public R sendMail(String phone) {
        // 1.邮箱地址书写是否正确
        // 2.判断缓存区中有无缓存（验证码是否已发）
        if (!StringUtils.isNoneEmpty(codeCache.get(phone))) {
            // 随机生成验证码
            String captcha = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
            String id = UUID.fastUUID().toString();
            EmailBody emailBody = new EmailBody("0", id, phone, captcha);

            messageRocketProducer.sendMessage(emailBody);

            //3.验证码放入缓存
            codeCache.put(phone, captcha);
            return R.success("验证码发送成功，请到邮箱进行查收");
        } else {
            return R.success("验证码已发送，稍等片刻！");
        }
    }

}
